<template>
  <div>
    <NavBar />
    <div class="publish-container">
      <!-- 大标题 -->
      <h1 class="main-title">感谢您为社区做出贡献</h1>
      <el-form ref="formRef" :model="form" label-width="100px" class="publish-form">
        <el-form-item label="标题">
          <el-input v-model="form.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="form.authorUsername" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            type="textarea"
            v-model="form.content"
            placeholder="请输入内容"
            class="textarea-content"
            :autosize="{ minRows: 10 }"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <div class="tags-input">
            <el-tag
              v-for="tag in dynamicTags"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="input-tag"
              size="small"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">
              + New Tag
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="资源文件">
          <div class="upload-container">
            <el-upload
              class="upload-demo"
              ref="uploadRef"
              :auto-upload="false"
              :file-list="fileList"
              :on-change="handleFileChange"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            </el-upload>
            <el-button class="upload-button" size="small" type="success" @click="uploadFile">上传文件</el-button>
          </div>
        </el-form-item>
        <el-form-item label="资源描述">
          <el-input type="textarea" v-model="form.resourceDescription" placeholder="请输入资源描述"></el-input>
        </el-form-item>
        <el-form-item class="submit-button-container">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import axiosInstance from '../plugins/axios'
import NavBar from '../components/NavBar.vue'
import { ElMessage } from 'element-plus'
import type { InputInstance, UploadFile } from 'element-plus'

const store = useStore()

interface PostForm {
  title: string
  authorUsername: string
  content: string
  tags: string[]
  resourceFileName: string
  resourceDescription: string
  categoryId: number | null
  resourceId: number | null // 添加 resourceId 属性
}

const form = ref<PostForm>({
  title: '',
  authorUsername: '',
  content: '',
  tags: [],
  resourceFileName: '',
  resourceDescription: '',
  categoryId: null,
  resourceId: null // 初始化 resourceId
})

const formRef = ref(null)
const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref<InputInstance>()
const categories = ref([])

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const fileList = ref<UploadFile[]>([]) // 确保 fileList 是一个数组

const handleFileChange = (file, files) => {
  fileList.value = files // 更新 fileList
}

const handleUploadSuccess = (response) => {
  console.log(response)
  if (response.fileName && response.category && response.category.id && response.id) {
    form.value.resourceFileName = response.fileName
    form.value.categoryId = response.category.id
    form.value.resourceId = response.id // 设置 resourceId
    ElMessage.success('资源上传成功')
  } else {
    ElMessage.error('上传响应中缺少必要的数据')
  }
}

const fetchCategories = async () => {
  try {
    const response = await axiosInstance.get('/categories/subcategories')
    categories.value = response.data
  } catch (error) {
    console.error('Error fetching categories:', error)
  }
}

const uploadFile = async () => {
  try {
    if (!fileList.value.length) {
      ElMessage.error('请先选择文件')
      return
    }

    if (!form.value.categoryId) {
      ElMessage.error('请先选择分类')
      return
    }

    const file = fileList.value[0]
    const formData = new FormData()
    formData.append('file', file.raw)
    formData.append('description', form.value.resourceDescription)
    formData.append('categoryId', form.value.categoryId.toString())
    formData.append('uploaderId', '1')

    const response = await axiosInstance.post('/resources/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    handleUploadSuccess(response.data)
  } catch (error) {
    ElMessage.error('文件上传失败')
    console.error('Error uploading file:', error)
  }
}

const handleSubmit = async () => {
  try {
    // 获取当前用户信息
    const user = store.getters.getUser
    if (!user || !user.id) {
      console.error('User ID is not available')
      ElMessage.error('用户未登录')
      return
    }

    // 处理标签
    const tags = dynamicTags.value.map(tag => ({ tag }))

    // 发送发帖请求
    const response = await axiosInstance.post('/posts', {
      title: form.value.title,
      content: form.value.content,
      userId: user.id, // 动态获取当前用户ID
      categoryId: form.value.categoryId,
      resourceId: form.value.resourceId,
      tags
    })

    ElMessage.success('帖子发布成功')
    console.log('Post submitted:', response.data)
  } catch (error) {
    ElMessage.error('帖子发布失败')
    console.error('Error submitting post:', error)
  }
}

onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.publish-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.main-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.publish-form {
  width: 800px; /* 设置宽度与帖子信息展示界面的宽度一致 */
}

.el-form-item {
  margin-bottom: 20px; /* 增加每行内容之间的间距 */
}

.textarea-content {
  min-height: 200px; /* 增大帖子内容输入框的高度 */
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.input-tag {
  flex-grow: 1;
  min-width: 200px;
}

.upload-container {
  display: flex;
  align-items: center;
}

.upload-button {
  margin-left: 70px; /* 向右移动 */
  margin-bottom: 8px;
}

.submit-button-container {
  display: flex;
  justify-content: center; /* 将提交按钮居中 */
}
</style>